import { defineStore } from 'pinia'
import { store } from '@/store'
import { logout, userLoginProfile } from '@/api/login'
import { deleteAccessToken, getAccessToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'

interface UserInfo {
  id: number
  nickname: string
  avatar: string
  roles: string[]
}

export const useUserStore = defineStore('user', {
  state: (): UserInfo => ({
    id: 0,
    nickname: '',
    avatar: '',
    roles: []
  }),

  getters: {
    getUserInfo(state: UserInfo): UserInfo {
      return state
    },

    getUserId(state: UserInfo): number {
      return state.id
    },

    getUserNickname(state: UserInfo): string {
      return state.nickname
    },

    getUserAvatar(state: UserInfo): string {
      return state.avatar
    },

    getUserRoles(state: UserInfo): string[] {
      return state.roles
    }
  },

  actions: {
    async setUserInfo() {
      if (!getAccessToken()) {
        ElMessage.error('获取当前用户信息失败：请先登录')
        return
      }

      const userInfo = await userLoginProfile()
      this.id = userInfo.id
      this.nickname = userInfo.nickname
      this.avatar = userInfo.avatar
      this.roles = userInfo.roles
    },

    async setUserId(id: number) {
      this.id = id
    },

    async setUserNickname(nickname: string) {
      this.nickname = nickname
    },

    async setUserAvtar(avatar: string) {
      this.avatar = avatar
    },

    async setUserRoles(roles: string[]) {
      this.roles = roles
    },

    async logout() {
      await logout()
      deleteAccessToken()
      this.resetUserInfo()
    },

    userInfoIsEmpty() {
      // 只需要判断编号和名称即可
      return !this.id || !this.nickname
    },

    resetUserInfo() {
      this.id = 0
      this.nickname = ''
      this.avatar = ''
      this.roles = []
    }
  }
})

export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
